package com.dongbo.recorder.screenrecord.ui.activity;

import android.content.pm.PackageManager;
import android.graphics.Color;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.dongbo.recorder.screenrecord.AppLpds;
import com.dongbo.recorder.screenrecord.Constants;
import com.dongbo.recorder.screenrecord.R;
import com.dongbo.recorder.screenrecord.base.BaseActivity;
import com.dongbo.recorder.screenrecord.bean.NetResponse;
import com.dongbo.recorder.screenrecord.bean.UserInfo;
import com.dongbo.recorder.screenrecord.dialog.CancelDialog;
import com.dongbo.recorder.screenrecord.prefrences.PreferencesRepository;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.gyf.immersionbar.ImmersionBar;

import java.io.IOException;

import butterknife.BindView;
import butterknife.OnClick;
import me.leefeng.promptlibrary.PromptButton;
import me.leefeng.promptlibrary.PromptButtonListener;
import me.leefeng.promptlibrary.PromptDialog;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * description：
 * author：lutengxuan
 * CreateDate：2020-05-07
 */
public class SettingActivity extends BaseActivity {

    @BindView(R.id.tv_cancel)
    TextView tvCancel;
    @BindView(R.id.btnOutLogin)
    TextView btnOutLogin;
    @BindView(R.id.tv_version)
    TextView tvVersion;

    @Override
    protected int getLayout() {
        return R.layout.activity_setting;
    }

    @Override
    protected void initView() {
        ImmersionBar.with(this)
                .fitsSystemWindows(true)
                .statusBarColor(R.color.white)
                .statusBarDarkFont(true)
                .init();
        if (TextUtils.isEmpty(AppLpds.getInstance().getUserId())) {
            btnOutLogin.setVisibility(View.GONE);
            tvCancel.setVisibility(View.GONE);
        } else {
            btnOutLogin.setVisibility(View.VISIBLE);
            tvCancel.setVisibility(View.VISIBLE);
        }

        try {
            String verName = getPackageManager().
                    getPackageInfo(getPackageName(), 0).versionName;
            tvVersion.setText("v" + verName);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

    }

    @Override
    protected void initData() {

    }

    @Override
    protected void initListener() {

    }

    @OnClick({
            R.id.btnLeft,
            R.id.tv_privacy,
            R.id.tv_agreement,
            R.id.tv_cancel,
            R.id.btnOutLogin})
    public void OnViewClick(View view) {
        switch (view.getId()) {
            case R.id.btnLeft:
                finish();
                break;
            case R.id.tv_cancel:
                PromptDialog promptDialog = new PromptDialog(this);

                final PromptButton confirm = new PromptButton("确定", new PromptButtonListener() {
                    @Override
                    public void onClick(PromptButton button) {
                        zhuxiao();
                    }
                });
                confirm.setTextColor(Color.parseColor("#ff0000"));
                promptDialog.showWarnAlert("你确定要注销该账号吗？", new PromptButton("取消", new PromptButtonListener() {
                    @Override
                    public void onClick(PromptButton button) {
                    }
                }), confirm);
//                cancelDialog();
                break;
            case R.id.btnOutLogin:
                PromptDialog promptDialog1 = new PromptDialog(this);

                final PromptButton confirm1 = new PromptButton("确定", new PromptButtonListener() {
                    @Override
                    public void onClick(PromptButton button) {
                        loginOut();
                    }
                });
                confirm1.setTextColor(Color.parseColor("#ff0000"));
                promptDialog1.showWarnAlert("你确定要退出吗？", new PromptButton("取消", new PromptButtonListener() {
                    @Override
                    public void onClick(PromptButton button) {
                    }
                }), confirm1);
                break;
            case R.id.tv_privacy:
                WebActivity.start(SettingActivity.this,
                        "",
                        Constants.YINSI);
                break;
            case R.id.tv_agreement:
                WebActivity.start(SettingActivity.this,
                        "",
                        Constants.FUWU);

                break;
        }
    }

    /**
     * 注销
     */
    private void cancelDialog() {
        CancelDialog mDialog = new CancelDialog(this,
                R.style.recharge_pay_dialog,
                new CancelDialog.OnDialogEventListener() {

                    @Override
                    public void onCancel() {

                    }

                    @Override
                    public void onShow() {
                        WebActivity.start(SettingActivity.this,
                                "",
                                Constants.BASE_URL
                                        + "app/article/u/protocolInfo?protocolId=865ba30501c841f3a53903860b6554ee");
                    }
                });
        mDialog.show();
    }

    private void zhuxiao() {
        OkHttpClient okHttpClient = new OkHttpClient();
        RequestBody body = new FormBody.Builder()
                .build();
        final Request request = new Request.Builder()
                .url(Constants.BASE_URL + "/app/user/deleteUser")
                .addHeader("Authorization", AppLpds.getInstance().getToken())
                .get()//默认就是GET请求，可以不写
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
//                requireActivity().runOnUiThread(() -> {
//                    Tt.show(requireActivity(), e.getMessage());
//                    SysAlertDialog.cancelLoadingDialog();
//                });

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String json = response.body().string();
                if (TextUtils.isEmpty(json)) {
                    return;
                }
                runOnUiThread(() -> {
//                    Log.i("ddd", "用户信息===" + json);
                    NetResponse<UserInfo> info = new Gson().fromJson(json, new TypeToken<NetResponse<UserInfo>>() {
                    }.getType());
                    if (null != info && info.getStatusCode() == 200) {
                        Toast.makeText(SettingActivity.this, "账号已注销", Toast.LENGTH_SHORT).show();
                        PreferencesRepository.getDefaultInstance().setString(Constants.PREFERENCE_USER_DATA, "");
                        PreferencesRepository.getDefaultInstance().setString(Constants.PREFERENCE_USER_TOKEN, "");
                        btnOutLogin.setVisibility(View.GONE);
                        tvCancel.setVisibility(View.GONE);
                        finish();
                    }
                });
            }
        });

    }


    private void loginOut() {
        OkHttpClient okHttpClient = new OkHttpClient();
        RequestBody body = new FormBody.Builder()
                .build();
        final Request request = new Request.Builder()
                .url(Constants.BASE_URL + "/logout")
                .addHeader("Authorization", AppLpds.getInstance().getToken())
                .get()//默认就是GET请求，可以不写
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
//                requireActivity().runOnUiThread(() -> {
//                    Tt.show(requireActivity(), e.getMessage());
////                    SysAlertDialog.cancelLoadingDialog();
//                });

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String json = response.body().string();
                if (TextUtils.isEmpty(json)) {
                    return;
                }
                runOnUiThread(() -> {
//                    Log.i("ddd", "用户信息===" + json);
                    NetResponse<UserInfo> info = new Gson().fromJson(json, new TypeToken<NetResponse<UserInfo>>() {
                    }.getType());
                    if (null != info && info.getStatusCode() == 200) {
                        Toast.makeText(SettingActivity.this, "账号已退出", Toast.LENGTH_SHORT).show();
                        PreferencesRepository.getDefaultInstance().setString(Constants.PREFERENCE_USER_TOKEN, "");
                        PreferencesRepository.getDefaultInstance().setString(Constants.PREFERENCE_USER_DATA, "");
                        btnOutLogin.setVisibility(View.GONE);
                        tvCancel.setVisibility(View.GONE);
                        finish();
                    }
                });
            }
        });

    }

    @Override
    protected void onResume() {
        super.onResume();
        if (AppLpds.getInstance().isLogin()) {
            btnOutLogin.setVisibility(View.VISIBLE);
            tvCancel.setVisibility(View.VISIBLE);
        } else {
            btnOutLogin.setVisibility(View.GONE);
            tvCancel.setVisibility(View.GONE);
        }
    }
}
